<?php

/*
Given the sequence S1 = {a,b,c,d,…,x,y,z,aa,ab,ac…. } and given that this sequence corresponds (term for term)
to the sequence S2 = {0,1,2,3,….}. Write code to convert an element of S2 to the corresponding element of S1.

We should have: 'a'=0, 'z' = 25, 'aa'=26, 'zz'=701, 'aaa'=702 ...

PHP can't straight away use char as integer like C, we have to use the int = ord( char ) and char = chr( int ) function pair.
When dealing with number to string or string to number, recursion is a very good choice.
*/

$tests = array("a", "z", "aa", "az", "zz", "aaa");

foreach ( $tests as $test ){
	echo $test." is ". getValue($test)."<br/>";
}

$values = array(0, 25, 26, 701, 702);
foreach ( $values as $value ){
	echo $value." is ". getString($value)."<br/>";
}

function getValue( $test ){
	$len = strlen( $test );
	if( $len <=  0 ){
		return -1;
	}
	$char = $test[$len-1];
	$cur = ord( $char ) - ord('a');
	return $cur + 26 * ( getValue( substr($test, 0, -1) ) + 1 );
}

function getString( $value ){
	$cur = $value % 26;
	$char = chr( $cur + ord('a') );
	$value = floor( $value / 26 );
	if( $value < 1 ){
		return $char;
	}
	else {
		return getString( $value - 1 ) . $char;
	}
}